package com.gopay.checkorder.service.task;

import com.gopay.common.domain.bank.BcdlMessage;
import com.gopay.common.domain.bank.BcdlResult;
import com.gopay.common.domain.bank.abc.bcdl.quyeryCQRA10.res.AbcApCqra10Excel;
import com.gopay.common.domain.bank.abc.bcdl.quyeryCQRA10.res.ApResCQRA10;
import com.gopay.common.util.DateUtils;
import com.gopay.common.util.FtpUtil;
import com.gopay.common.util.SendMail;
import com.gopay.remote.bank.BcdlInteractRemoteService;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.poi.hssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 农行下载对账文件
 * 20170919
 * @author ssj
 * @AbcDownloadOrderTaskImpl.java
 */
@SuppressWarnings("all")
public class AbcDownloadOrderTaskImpl implements Task {
    private static Logger logger = LoggerFactory
            .getLogger(AbcDownloadOrderTaskImpl.class);
    @Resource(name = "bankBcdlClient")
    private BcdlInteractRemoteService bankBcdlClient;
    @Resource(name = "abcpayConfig")
    private Map<String, String> abcpayConfig;

    private String bank;
    /**
     * 时间格式：yyyy-MM-dd' 'HH:mm:ss'.
     */
    public static String yyyy_MM_dd_HH_mm = "yyyyMMdd HH:mm";
    public void doTask() {
        try {
            StopWatch sw = new StopWatch();
            sw.start();

            if ("off".equals(abcpayConfig.get("mailSwitch"))) {
                logger.error("AbcDownloadOrderTaskImpl: 不进行ftp操作直接返回!");
                return;
            }

            String configExcelPath = abcpayConfig.get("ftp.locpath")+ DateUtils.format(new Date(), "yyyy-MM-dd") + "/";
            String FPath = DateUtils.getYesterday();
            FtpUtil ftpUtil = new FtpUtil();
            String payFileName = "";
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm");

            String dateType = "";
            String DateStr1 = getCurrDate();
            String DateStr2 = GetDate() + " 03:30";
            String DateStr3 = GetDate() + " 10:30";
            Date dateTime1 = dateFormat.parse(DateStr1);
            Date dateTime2 = dateFormat.parse(DateStr2);
            Date dateTime3 = dateFormat.parse(DateStr3);
            String startDate = "";
            String endDate = "";
            BcdlResult result = null;
            BcdlMessage base = new BcdlMessage();
            base.setBank("ABC");
            //每天凌晨3点半执行一次,获取前一天的农行对账信息
            if (dateTime1.getTime() == dateTime2.getTime()) {
                // 前一天日期
                startDate = DateUtils.getYesterday();
                endDate = startDate;
                base.setOrderDate(startDate);
                dateType = "0330";
                logger.info("AbcDownloadOrderTaskImpl 上午03:30 开始执行农行对账明细信息当,日期为:" + startDate);
            } else if (dateTime1.getTime() == dateTime3.getTime()) {//上午10:30 开始执行农行对账明细信息当
                //开始日期
                startDate = GetDate();
                base.setOrderDate(startDate);
                logger.info("AbcDownloadOrderTaskImpl 上午10:30 开始执行农行对账明细信息当,日期为:" + startDate);
                dateType = "1030";

            } else {
                //开始日期  下午三点半开始执行一次
                startDate = GetDate();
                base.setOrderDate(startDate);
                dateType = "1530";
                logger.info(" AbcDownloadOrderTaskImpl 上午15:30 开始执行农行对账明细信息当,日期为:" + startDate);
            }
            //excel 文件名称
            String fileNameExcel = "ABC_DCBL_" + GetDate() + "_" + getGregorianCalendar() + "_" + dateType + ".xls";
            String fileNamePathExcel = configExcelPath + fileNameExcel;
            result = bankBcdlClient.queryAcctDetail(base);
            logger.info("文件名称:" + result.getDefaultModel());
            ApResCQRA10 ar10 = (ApResCQRA10) result.getDefaultModel();
            if (ar10 != null) if (ar10.getRespcode().equals("0000")) {
                //文件名称
                payFileName = ar10.getCmp().getBatchfilename();

                String url =abcpayConfig.get("ftp.url");
                String username =abcpayConfig.get("ftp.username");
                String password =abcpayConfig.get("ftp.password");
                //下载本地目录
                String locpath = configExcelPath;
                String encoding = "UTF-8";
                int port = 15999;
                List payNames = new ArrayList();//农行对账文件名称
                List names = new ArrayList();
                // 目录不存在则创建目录
                File dir = new File(locpath);
                if (!dir.exists()) dir.mkdirs();
                // 判断本地服务器是否存在农行对账文件
                if (!(new File(locpath + payFileName).exists())) {
                    logger.info("农业银行对账 job 开始");
                    if (ftpUtil.exist(url, port, username, password, FPath, payFileName, encoding)) {
                        logger.error("AbcDownloadOrderTaskImpl " + payFileName + "exist!");
                        // 下载i支付快捷支付对账文件
                        if (FtpUtil.downFile(url, port, username, password, FPath, payFileName, locpath, payFileName, encoding)) {
                            logger.error("AbcDownloadOrderTaskImpl " + payFileName + " downLoad success!");
                            payNames.add(payFileName);
                        }
                        logger.error("AbcDownloadOrderTaskImpl payNames=" + payNames);
                        names.addAll(payNames);
                        ;
                    } else logger.error("AbcDownloadOrderTaskImpl local " + payFileName + " 支付对账文件已成功下载, 不再进行ftp操作!");

                    //开始组装成excel格式文件发送邮件
                    exportFeedBack(configExcelPath, fileNamePathExcel, fileNameExcel, configExcelPath + payFileName);
                    //发送邮件
                    sendMessage(fileNameExcel, configExcelPath);
                } else {
                    //先判断exce是否存在,存在则直接发送邮件,不需要调用查询银行接口
                    File file = new File(fileNamePathExcel);
                    //先判断txt是否存在,存在则直接发送邮件,不需要调用查询银行接口
                    File fileXml = new File(locpath + payFileName);
                    if (fileXml.exists()) {
                        if (!file.exists()) {
                            //组装数据包装成excel格式
                            exportFeedBack(configExcelPath, fileNamePathExcel, fileNameExcel, locpath + payFileName);
                        }
                        //发送邮件
                        sendMessage(fileNameExcel, configExcelPath);
                        logger.info("AbcDownloadOrderTaskImpl  直接发送,早已生成excel格式数据信息");
                    }
                }

            } else {
                logger.info("农业银行对账错误信息提示  error email  ：" + ar10.getRespcode() + ar10.getRxtinfo());
            }

            logger.info("农业银行对账 job 结束");

            sw.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取当前时间(格式:yyyyMMddHHmm)
     *
     * @return
     */
    public static String getCurrDate() {
        return getCurrDate(yyyy_MM_dd_HH_mm);
    }


    public void sendMessage(String fileNameExcel, String excel_Path) {
        try {
            List sendFile = new ArrayList();
            List names = new ArrayList();
            String[] cc = abcpayConfig.get("sendmail.cc").split(","); // 获取多个抄送人
            List<String> ccList = Arrays.asList(cc);
            names.add(fileNameExcel);
            //附件标题
            String subject = "农行对账文件明细下载";

            logger.info("AbcDownloadOrderTaskImpl  fileNameExcel 路径:" + fileNameExcel + "excel_Path路径:" + excel_Path);
            // 附件内容
            String messageText = DateUtils.format(new Date(), "yyyy-MM-dd") + ": 农行对账文件请您见附件查收!" + fileNameExcel;
            for (int i = 0; i < names.size(); i++) {
                sendFile.add(excel_Path + (String) names.get(i));
            }
            logger.error("sendMessage  config:--host:"
                    + abcpayConfig.get("sendmail.host") + "----sender:"
                    + abcpayConfig.get("sendmail.sender") + "----username:"
                    + abcpayConfig.get("sendmail.username")
                    + "----password:"
                    + abcpayConfig.get("sendmail.password")
                    + "----receiver:"
                    + abcpayConfig.get("sendmail.receiver"));
            // 发送邮件
            SendMail.sendMessage(abcpayConfig.get("sendmail.host"),
                    abcpayConfig.get("sendmail.sender"),
                    abcpayConfig.get("sendmail.username"),
                    abcpayConfig.get("sendmail.password"),
                    abcpayConfig.get("sendmail.receiver"), subject,
                    messageText, "text/html;charset=gb2312", ccList, sendFile,
                    names);
            logger.info("AbcDownloadOrderTaskImpl  农行对账明细邮件发送成功!");
        } catch (MessagingException e) {
            logger.error("AbcDownloadOrderTaskImpl 农行对账文件明细发送邮件失败!", e);
            e.printStackTrace();
            ;

        }

    }

    /**
     * 上午 下午转换
     *
     * @return
     */
    public String getGregorianCalendar() {
        GregorianCalendar ca = new GregorianCalendar();
        //结果为“0”是上午 结果为“1”是下午
        String AM_PM = "";
        if (ca.get(GregorianCalendar.AM_PM) == 0) {
            AM_PM = "AM";
        } else {
            AM_PM = "PM";
        }
        return AM_PM;
    }

    /**
     * 返回系统当前日期
     *
     * @return
     */
    public  String GetDate() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String date = format.format(new Date());
        return date;
    }

    public void setBank(String bank) {
        this.bank = bank;
    }

    public String getBank() {
        return bank;
    }

    /**
     * 获取当前时间
     *
     * @param pattern 格式
     * @return
     */
    public static String getCurrDate(String pattern) {
        long d = System.currentTimeMillis();
        Date date = new Date(d);

        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }

    public static HSSFWorkbook getHSSFWorkbook(String sheetName, String[] title, String[][] values, HSSFWorkbook wb) {
        // 第一步，创建一个webbook，对应一个Excel文件
        if (wb == null) {
            wb = new HSSFWorkbook();
        }
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet(sheetName);
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow(0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

        HSSFCell cell = null;
        //创建标题
        for (int i = 0; i < title.length; i++) {
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(style);
        }
        //创建内容
        for (int i = 0; i < values.length; i++) {
            row = sheet.createRow(i + 1);
            for (int j = 0; j < values[i].length; j++) {
                row.createCell(j).setCellValue(values[i][j]);
            }
        }
        return wb;
    }

    public static List<Object> readFileByLines(String fileName) {
        File file = new File(fileName);
        BufferedReader reader = null;
        List<Object> list = new LinkedList<Object>();
        String tempString = "";
        try {
            System.out.println("以行为单位读取文件内容，一次读一行");
            InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "GBK");
            reader = new BufferedReader(isr);
            int line = 1;
            //一次读一行，读入null时文件结束
            while ((tempString = reader.readLine()) != null) {
                //把当前行号显示出来
//                System.out.println("line " + line + ": " + tempString);
                line++;
                list.add(tempString);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return list;
    }


    /**
     * 写入文件
     *
     * @param writePath 文件路径
     */
    public static final void write(String excel_Path, String writePath, String writeTxt) {
        try {
            File filemk = new File(excel_Path);
            //创建目录
            if (!filemk.exists()) {
                filemk.mkdirs();
            }
            File f = new File(writePath);
//            if (!f.exists()) {
//                f.createNewFile();
//            }
            OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f, true), "UTF-8");
            BufferedWriter writer = new BufferedWriter(write);
            writer.write(writeTxt);
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param fileNamePathExcel excel路径
     * @param fileNameExcel     exce文件名称
     * @param fileNamePathTxt   记事本路径
     */
    public static void exportFeedBack(String excexPath, String fileNamePathExcel, String fileNameExcel, String fileNamePathTxt) {
//        List<Object> listObj = readFileByLines(fileNamePathTxt);
        List<Object> listObj = readFileByLines(fileNamePathTxt);
        List<AbcApCqra10Excel> orderList = new ArrayList<AbcApCqra10Excel>();
        if (listObj.size() > 0) {
            for (int i = 0; i < listObj.size(); i++) {
                Object[] obj = listObj.get(i).toString().split("\\|");
                if (obj != null) {
                    AbcApCqra10Excel excelvo = new AbcApCqra10Excel();
                    //交易时间 TimeStab
                    excelvo.setTimeStab(obj[4].toString());

                    if (obj[18].toString().contains("-")) {
                        //收入
                        excelvo.setInAmt("0.00");
                        //支出`
                        excelvo.setPayAmt(obj[18].toString().replace("-",""));
                    } else {
                        //收入
                        excelvo.setInAmt(obj[18].toString().replace("-",""));
                        //支出
                        excelvo.setPayAmt("0.00");
                    }
                    //余额
                    excelvo.setBal(obj[19].toString());
                    //交易行名  7
                    if (obj[7].equals("999999")) {
                        excelvo.setTranBankName("全行资金清算专属行部");
                    } else if (obj[7].equals("110434")) {
                        excelvo.setTranBankName("中国农业银行股份有限公司北京三元支行");
                    } else {
                        excelvo.setTranBankName(obj[7].toString());
                    }
                    //对方省市
//                    excelvo.setBranchProv("");
                    //对方账号
                    excelvo.setBankNo(obj[11].toString());
                    //姓名
                    excelvo.setAccName(obj[13].toString());
                    //用途 附言
                    excelvo.setPostScript(obj[31].toString());
                    orderList.add(excelvo);
                }
            }
        }
        //文件名称
        String fileName = fileNameExcel;
        String[] title = new String[]{"交易时间", "收入金额", "支出金额", "账户余额", "交易行名", "对方账号", "对方户名", "交易用途"};
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int size = orderList.size();
        String[][] values = new String[size][];
        int j = 0;
        for (int i = 0; i < orderList.size(); i++) {
            //将对象内容转换成string
            AbcApCqra10Excel body = orderList.get(i);
            //循环便利
            values[j] = new String[title.length];
            //交易时间 TimeStab
            values[j][0]  = format.format(DateUtils.strToDate(body.getTimeStab(),"yyyyMMddHHmmssSSSSSS"));
            //收入
            values[j][1] = body.getInAmt();
            //支出
            values[j][2] = body.getPayAmt();
            //余额
            values[j][3] = body.getBal();
            //交易行名
            values[j][4] = body.getTranBankName();
            //对方省市
//            values[j][5] = body.getBranchProv();
            //对方账号
            values[j][5] = body.getBankNo();
            //对方户名
            values[j][6] = body.getAccName();
            //用途 附言
            values[j][7] = body.getPostScript();
            j++;
        }

        HSSFWorkbook wb = getHSSFWorkbook(fileName, title, values, null);
        //将文件存到指定位置
        try

        {
            File filemk = new File(excexPath);
            //创建目录
            if (!filemk.exists()) {
                filemk.mkdirs();
            }
            File file = new File(excexPath + fileName);
            OutputStream out = new FileOutputStream(file, true);
            wb.write(out);
            out.flush();
            out.close();
        } catch (
                Exception e)

        {
            e.printStackTrace();
        }

    }
}
